<template>
    <div>
        <el-dialog :title="props.isAdd ? '添加角色' : '编辑角色'" v-model="props.isShow" center :before-close="beforeClose">
            <el-form :model="roleForm" :rules="rules" ref="roleRef">
                <el-form-item label="角色名称" :label-width="formLabelWidth" prop="rolename">
                    <el-input v-model="roleForm.rolename" autocomplete="off" />
                </el-form-item>
                <el-form-item label="角色权限" :label-width="formLabelWidth" v-model="roleForm.menus">
                    <el-tree ref="treeRef" :data="store.getters['menu/getMenu']" show-checkbox node-key="id" :props="{
                        children: 'children',
                        label: 'title',
                    }" default-expand-all check-strictly />
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="roleForm.status"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" :active-value="1"
                        :inactive-value="2" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel(roleRef)">取消</el-button>
                    <el-button type="primary" @click="sure(roleRef)">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang='ts' setup>
import { defineProps, defineEmits, ref, reactive, defineExpose, useAttrs } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElTree } from 'element-plus'
import { roleAdd, roleEdit, roleInfo } from '../../request/api'
// import store from '../../store'
import {useStore} from 'vuex'
let store = useStore()
const formLabelWidth = '140px'

// tree树形控件
// 能够取出 树节点的选中值 是数组类型
// 但是后端要求我们传入 “1,2,1” 数组转字符串join
interface Tree {
    id: number
    label: string
    children?: Tree[]
}
const treeRef = ref<InstanceType<typeof ElTree>>()

//父传子  接收数据
let props = defineProps({
    isShow: Boolean,
    isAdd: Boolean
})

//子传父
let emit = defineEmits(['cancel'])

//关闭x号事件
const beforeClose = (done: any) => {
    done()
    cancel(roleRef.value)
}

let newId = 0

let roleForm = ref({
    rolename: '',//角色名称string
    menus: '',//角色权限 id数组'2,3,4' 字符串
    status: 1,//状态1正常2禁用number
})

//取消事件
const cancel = (formEl?: FormInstance | undefined) => {
    emit('cancel', false)
    if (!formEl) return
    roleForm.value = {
        rolename: '',//角色名称string
        menus: '',//角色权限 id数组'2,3,4' 字符串
        status: 1,//状态1正常2禁用number
    }
    //清除表单验证
    formEl.resetFields()
    //清空tree树形结构样式
    treeRef.value!.setCheckedKeys([])
}

const roleRef = ref<FormInstance>()
const sure = async (formEl?: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(val => {
        if (val) {
            console.log(roleForm.value, '角色表单');
            roleForm.value.menus = treeRef.value!.getCheckedKeys(false).join(',')
            if (props.isAdd) {
                roleAdd(roleForm.value).then(res => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        store.dispatch('role/getRoleListActions')
                        menuList()
                        cancel(formEl)
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            } else {
                roleEdit({ ...roleForm.value, id: newId }).then(res => {
                    if (res.code == 200) {
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                        store.dispatch('role/getRoleListActions')
                        menuList()
                        cancel(formEl)
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            }
        }
    })
}

const rules = reactive<FormRules>({
    rolename: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 2, max: 8, message: '长度为 3 到 8个字符', trigger: 'blur' },
    ]
})

//数据回显
const lookup = (id: number) => {
    roleInfo({ id }).then((res: any) => {
        // console.log(id);    
        roleForm.value = res.list
        // menuForm.value.id = id
        // console.log(res);
        newId = id
        treeRef.value!.setCheckedKeys(roleForm.value.menus ? roleForm.value.menus.split(',') : [])
    })
}

defineExpose({
    lookup
})

//调用菜单管理行动
const menuList = () => {
    //减少对服务端发起请求，如何实现？ 判断菜单列表是否存在
    if (store.getters['menu/getMenu'].length == 0) {
        //调用菜单行动
        store.dispatch('menu/getMenuListAction')
    }
}
menuList()
</script>
<style lang='less' scoped></style>